package leetcode41_50;

import com.sun.jmx.remote.internal.ArrayQueue;
import leetcode31_40.Solution39;
import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shhjiang_001
 * @create 2020-06-17 12:54
 */

        /*
        给定 n 个非负整数表示每个宽度为 1 的柱子的高度图，计算按此排列的柱子，下雨之后能接多少雨水。
        示例:

        输入: [0,1,0,2,1,0,1,3,2,1,2,1]
        输出: 6
        */
public class Solution42 {
    int res = 0;
    public int trap(int[] height) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i:height){
            list.add(i);
        }
        method(list);
        return res;
    }

    private void method(List<Integer> list) {
        if (list.size()==0) return;
        while (list.size()>=1&& list.get(0) <= 0 ){
            list.remove(0);
        }
        while (list.size()>=1 && list.get(list.size()-1)<=0 ){
            list.remove(list.size()-1);
        }
        res = (int) (res + list.stream().filter(s->s<=0).count());
        List<Integer> collect = list.stream().map(s -> s = s - 1).collect(Collectors.toList());
        method(collect);

    }

    public int trap1(int[] height) {
        if (height==null || height.length==0) return 0;
        int big = 0;
        for (int i = 0;i <height.length;i++ ){
            if (height[i]>height[big]) big = i;
        }
        int[] ints = new int[big+1];
        int[] ints1 = new int[height.length - big];
        for (int i = 0 ;i < big+1; i++){
            ints[i] = height[i];
        }
        for (int i = 0;i<height.length-big;i++){
            ints1[i] = height[height.length-1-i];
        }
        int res1 = method(ints);
        int res2 = method(ints1);
        return res1+res2;

    }

    private int method(int[] height) {
        int res = 0;
        int le = 0,ri = 0;
        while (le < height.length){
            if (height[le] <= height[ri] && ri-le>=2){
                for (int i = le;i < ri-1;i++){
                    res = res + height[le]-height[i+1];
                }
                le = ri;
            }else if(height[le] <= height[ri]) {
                le = ri;
                ri++;
            }else {
                ri++;
            }
            if (ri >= height.length){
                le++;
                ri = le;
            }
        }
        return res;
    }

    @Test
    public void test() {
        Solution42 solution42 = new Solution42();
//        System.out.println(Arrays.asList(new int[]{1, 2, 3}).toString());
        int trap = solution42.trap1(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});
        System.out.println(trap);
    }
}
